//
//  HomeViewController.m
//  翼安保
//
//  Created by duzhi on 2024/4/15.
//

#import "HomeViewController.h"
#import "LoginViewController.h"
#import "UserInfo.h"
#import "HomeIconCollectionViewCell.h"
#import "HomeModel.h"
#import <WebKit/WebKit.h>
#import "DetailListJumpHelp.h"
#import "DetailListJumpHelp.h"
#import "HomeApi.h"
#import "RegisterCheckViewController.h"
#import "PulishFilter.h"
#import "PlaceInfoViewController.h"

@interface HomeViewController ()<UICollectionViewDelegate,UICollectionViewDataSource>
@property (strong, nonatomic) UIImageView  *backImageView;
@property (strong, nonatomic) UILabel      *nameL;
@property (strong, nonatomic) UILabel      *bottomTipL;
@property (strong, nonatomic) UILabel      *badgeL;
@property (strong, nonatomic) UICollectionView      *collectionView;

@property (strong, nonatomic) NewsBigButton  *loginOutButton;
@property (nonatomic ,strong) UIButton *loginOutButton2;
@property (strong, nonatomic) UserInfo     *userInfo;
@property (strong, nonatomic) NSArray      *datas;

@property (strong, nonatomic) DetailListJumpHelp   *jumpHelp;
@end

@implementation HomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBar.hidden = YES;
    [self checkLoginStatus];
    [self foodExpairChange];
    self.jumpHelp = [DetailListJumpHelp new];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginSuccess) name:NotifcationName_LoginSuccess object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginOut) name:NotifcationName_LoginOutSuccess object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(foodExpairChange) name:NotifcationName_foodExpairChange object:nil];
}

- (void)loginSuccess {
   [self checkLoginStatus];
}

- (void)loginOut {
   [self checkLoginStatus];
}

-(void)foodExpairChange {
    id userInfo =  [[NSUserDefaults standardUserDefaults] objectForKey:KUserInfo];
    if (userInfo) {
        [[AFNNetWorkManager shareAFNNetWorkManager] Get:getMyFoodsUrl parameters:nil success:^(NSURLSessionDataTask *task, Result *result) {
            if (result.code == 200) {
                NSMutableArray *datas = [DetailListModel mj_objectArrayWithKeyValuesArray:result.data];
                __block int num = 0;
                [datas enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    DetailListModel*model = obj;
                    if ([model.timeState isEqualToString:@"超期"]||[model.timeState isEqualToString:@"临期"]) {
                        num++;
                    }
                }];
                _badgeL.hidden = num==0?YES:NO;
                if (num>0) {
                    self.badgeL.text = [NSString stringWithFormat:@"%d",num];
                    CGFloat w = [self.badgeL.text sizeWithFont:self.badgeL.font maxWidth:relativeWidth(200)].width+1;
                    w = w < relativeWidth(18)?relativeWidth(18):w;
                    CGFloat padding = w == relativeWidth(18)?0:relativeWidth(18);
                    [self.badgeL mas_updateConstraints:^(MASConstraintMaker *make) {
                        make.width.mas_equalTo(w+padding);
                    }];
                }
               
            }
        } failure:^(NSURLSessionDataTask *task, NSError *error) {
            
        }];
    }else{
        _badgeL.hidden = YES;
    }
}

- (void)checkLoginStatus {
   id userInfo =  [[NSUserDefaults standardUserDefaults] objectForKey:KUserInfo];
   if (userInfo) {
       self.userInfo = [UserInfo mj_objectWithKeyValues:userInfo];
       NSMutableArray *datas = @[
          @{
               @"title":@"输码查询",
               @"icon":@"home_input"
           },@{
               @"title":@"扫码查询",
               @"icon":@"home_scan"
           },@{
               @"title":@"NFC查询",
               @"icon":@"home_nfc"
           },@{
               @"title":@"我的领用",
               @"icon":@"home_myget"
           },@{
               @"title":@"用品领用",
               @"icon":@"home_get"
           }
       ].mutableCopy;
       if (![self.userInfo.role isEqualToString:@"1"]) {
           [datas addObject:@{
            @"title":@"注册审批",
            @"icon":@"home_agree"
           }];
       }
       [datas addObject:@{
        @"title":@"个人信息",
        @"icon":@"home_info"
       }];
       self.datas = [HomeModel mj_objectArrayWithKeyValuesArray:datas];
       if(!self.backImageView){
           [self creatUI];
       }
       [self getBottomTip];
       self.nameL.text = self.userInfo.name;
   }else{
       [self.navigationController pushViewController:[LoginViewController new] animated:NO];
   }
}

- (void)creatUI {
    self.view.backgroundColor = UIColorFromRGB(0xF9F9F9);
    self.backImageView = [UIImageView new];
    self.backImageView.userInteractionEnabled = YES;
    self.backImageView.image = [UIImage imageNamed:@"bg_login"];
    [self.view addSubview:self.backImageView];
    [self.backImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.mas_equalTo(0);
        make.height.mas_equalTo(768/1024.f*ScreenWidth);
    }];
    
    UILabel *titleL = [UILabel new];
    titleL.text = @"安全用品全生命周期监管平台";
    titleL.font = [UIFont boldSystemFontOfSize:relativeWidth(20)];
    titleL.textColor = [UIColor whiteColor];
    [self.backImageView addSubview:titleL];
    [titleL mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(0);
        make.bottom.mas_equalTo(relativeWidth(-150));
    }];
    
    UIImageView *avatarIcon = [UIImageView new];
    avatarIcon.image = [UIImage imageNamed:@"home_avatar"];
    [self.backImageView addSubview:avatarIcon];
    [avatarIcon mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(relativeWidth(15));
        make.centerY.mas_equalTo(self.view.mas_top).offset(kiPhoneX_Top_Height+22);
        make.width.height.mas_equalTo(26);
    }];
    
    self.nameL = [UILabel new];
    self.nameL.text = self.userInfo.name;
    self.nameL.font = [UIFont systemFontOfSize:relativeWidth(16)];
    self.nameL.textColor = [UIColor whiteColor];
    [self.backImageView addSubview:self.nameL];
    [self.nameL mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(avatarIcon.mas_centerY);
        make.left.mas_equalTo(avatarIcon.mas_right).offset(relativeWidth(1));
    }];

    self.loginOutButton = [NewsBigButton new];
    [self.loginOutButton setBackgroundImage:[UIImage imageNamed:@"home_loginout"] forState:0];
    [self.loginOutButton addTarget:self action:@selector(loginOutClick) forControlEvents:UIControlEventTouchUpInside];
    [self.backImageView addSubview:self.loginOutButton];
    [self.loginOutButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(relativeWidth(-15));
        make.centerY.mas_equalTo(avatarIcon.mas_centerY);
        make.width.height.mas_equalTo(relativeWidth(26));
    }];
    
    self.loginOutButton2 = [UIButton new];
    [self.loginOutButton2 addTarget:self action:@selector(loginOutClick) forControlEvents:UIControlEventTouchUpInside];
    [self.backImageView addSubview:self.loginOutButton2];
    [self.loginOutButton2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(0);
        make.centerY.mas_equalTo(avatarIcon.mas_centerY);
        make.height.mas_equalTo(relativeWidth(44));
        make.width.mas_equalTo(relativeWidth(80));
    }];
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    layout.minimumInteritemSpacing = 0;
    layout.minimumLineSpacing = 0;
    UICollectionView *classifyV = [[UICollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:layout];
    classifyV.bounces = NO;
    classifyV.contentInset = UIEdgeInsetsMake(relativeWidth(30), relativeWidth(30), relativeWidth(30), relativeWidth(30));
    classifyV.backgroundColor = [UIColor whiteColor];
    classifyV.showsVerticalScrollIndicator = NO;
    classifyV.showsHorizontalScrollIndicator = NO;
    [classifyV registerClass:[HomeIconCollectionViewCell class] forCellWithReuseIdentifier:@"HomeIconCollectionViewCell"];
    classifyV.delegate = self;
    classifyV.dataSource = self;
    classifyV.layer.cornerRadius = relativeWidth(5);
    [self.view addSubview:classifyV];
    [classifyV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(relativeWidth(15));
        make.right.mas_equalTo(relativeWidth(-15));
        make.top.mas_equalTo(self.backImageView.mas_bottom).offset(relativeWidth(60));
        make.height.mas_equalTo(relativeWidth(40)*3+relativeWidth(5)*3+relativeWidth(20)*3+relativeWidth(20)*2+relativeWidth(30)*2);
    }];
    self.collectionView = classifyV;
    
    self.bottomTipL = [UILabel new];
    self.bottomTipL.numberOfLines = 0;
    self.bottomTipL.font = [UIFont systemFontOfSize:relativeWidth(14)];
    self.bottomTipL.textColor = [[UIColor blackColor] colorWithAlphaComponent:0.7];
    [self.view addSubview:self.bottomTipL];
    [self.bottomTipL mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(0);
        make.bottom.mas_equalTo(-kiPhoneX_Bottom_Height+relativeWidth(-20));
    }];
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.datas.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    HomeModel *model = [self.datas objectAtIndex:indexPath.row];
    HomeIconCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"HomeIconCollectionViewCell" forIndexPath:indexPath];
    cell.model = model;
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake(relativeWidth(40), relativeWidth(40)+relativeWidth(5)+relativeWidth(20));
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return relativeWidth(20);
}


- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    CGFloat num = floor((ScreenWidth - relativeWidth(40)*3-relativeWidth(15)*2-relativeWidth(30)*2)/2.f);
    return num;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        [self.jumpHelp inputSearch:self type:0];
    }
    if (indexPath.row == 1) {
        [self.jumpHelp scanSearch:self type:0];
    }
    if (indexPath.row == 2) {
        [self.jumpHelp NFCSearch:self type:0];
    }
    if (indexPath.row == 3) {
        [self.jumpHelp getMyFoods:self];
    }
    if (indexPath.row == 4) {
        UIAlertController *alertview = [UIAlertController alertControllerWithTitle:@"请选择以下任一种方式开始查询：" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        UIAlertAction *input = [UIAlertAction actionWithTitle:@"输码查询" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self.jumpHelp inputSearch:self type:2];
        }];
        UIAlertAction *scan = [UIAlertAction actionWithTitle:@"扫码查询" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self.jumpHelp scanSearch:self type:2];
        }];
        UIAlertAction *nfc = [UIAlertAction actionWithTitle:@"NFC查询" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self.jumpHelp NFCSearch:self type:2];
        }];
        UIAlertAction *cance = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        [alertview addAction:input];
        [alertview addAction:scan];
        [alertview addAction:nfc];
        [alertview addAction:cance];
        [self presentViewController:alertview animated:YES completion:nil];
    }
    if (indexPath.row == 5) {
        RegisterCheckViewController *vc = [RegisterCheckViewController new];
        [self.navigationController pushViewController:vc animated:NO];
    }
    if (indexPath.row == 6) {
        PlaceInfoViewController *vc = [PlaceInfoViewController new];
        [self.navigationController pushViewController:vc animated:NO];
    }
}

- (void)loginOutClick {
    if ([PulishFilter isComedMyDay]) {
        [self userLoginOut];
    }else{
        UIAlertController *alertview = [UIAlertController alertControllerWithTitle:@"请选择：" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        UIAlertAction *loginOut = [UIAlertAction actionWithTitle:@"退出登录" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self userLoginOut];
        }];
        UIAlertAction *zhuxiaoOut= [UIAlertAction actionWithTitle:@"注销账号" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self userLoginOut];
            [[NSUserDefaults standardUserDefaults] setObject:@"YES" forKey:@"isDelete"];
        }];
        UIAlertAction *cance = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        [alertview addAction:loginOut];
        [alertview addAction:zhuxiaoOut];
        [alertview addAction:cance];
        [self presentViewController:alertview animated:YES completion:nil];
    }
}

- (void)userLoginOut {
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:KUserInfo];
    [[NSUserDefaults standardUserDefaults] synchronize];
    [[NSNotificationCenter defaultCenter] postNotificationName:NotifcationName_LoginOutSuccess object:nil];
    [[NSNotificationCenter defaultCenter] postNotificationName:NotifcationName_foodExpairChange object:nil];
}

- (void)getBottomTip {
    NSURL *url = [NSURL URLWithString:@"http://120.55.103.206:8002/info.asp"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
     
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:
    ^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (!error) {
            //GBK
            NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
            NSString *content = [[NSString alloc] initWithData:data encoding:enc];
            dispatch_async(dispatch_get_main_queue(), ^{
                self.bottomTipL.text = content;
            });
        } else {
            NSLog(@"Error: %@", error.localizedDescription);
        }
    }];
    [task resume];
}

- (UILabel *)badgeL {
    if (!_badgeL) {
        _badgeL = [UILabel new];
        _badgeL.backgroundColor = [UIColor redColor];
        _badgeL.layer.cornerRadius = relativeWidth(9);
        _badgeL.layer.masksToBounds = YES;
        _badgeL.textColor = [UIColor whiteColor];
        _badgeL.font = [UIFont systemFontOfSize:relativeWidth(9)];
        _badgeL.textAlignment = NSTextAlignmentCenter;
        [self.view addSubview:_badgeL];
        UICollectionViewCell *cell = [self.collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForRow:3 inSection:0]];
        if (cell&&cell.superview) {
            [self.badgeL mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.mas_equalTo(cell.mas_top).offset(relativeWidth(9));
                make.centerX.mas_equalTo(cell.mas_right).offset(relativeWidth(-9));
                make.width.height.mas_equalTo(relativeWidth(18));
            }];
        }
    }
    return _badgeL;
}

@end
